package org.itboys.pay.alipay;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.itboys.commons.CommonConstants;
import org.itboys.commons.utils.time.TimeUtils;
import org.itboys.pay.constant.AlipayConfig;
import org.itboys.pay.constant.PayConfigHolder;
import org.itboys.pay.constant.PayConstants;

import com.google.common.collect.Maps;

/**
 * 支付宝APP支付
 * @author huml
 *
 */
public class AlipayMobileService {
	
	/**
	 * 支付宝申请退款
	 * @param refundNotifyUrl  退款回调链接
	 * @param outTradeNo  订单编号
	 * @param totalFee  金额
	 * @return
	 */
	public static String refund(String refundNotifyUrl, String outTradeNo, String totalFee){
		Map<String, String> sParaTemp = Maps.newHashMap();
		sParaTemp.put("service", "refund_fastpay_by_platform_pwd");
		sParaTemp.put("partner", PayConfigHolder.getAlipayPartner());
		sParaTemp.put("_input_charset", AlipayConfig.input_charset);
		sParaTemp.put("notify_url", refundNotifyUrl);
		sParaTemp.put("seller_user_id", PayConfigHolder.getAlipayPartner());
		sParaTemp.put("refund_date", TimeUtils.format(new Date(), CommonConstants.DATE.FORMAT_DEFAULT));
		sParaTemp.put("batch_no", outTradeNo);
		sParaTemp.put("batch_num", "1");
		sParaTemp.put("detail_data", outTradeNo+"^"+totalFee+"^"+"协商退款");
		String result = AlipaySubmit.buildRequest(sParaTemp, "post", "确认退款");
		return result;
	}
	
	/**
	 * 支付宝手机支付 验证异步回调并返回结果
	 * @return AlipayWapResult 
	 */
	@SuppressWarnings("rawtypes")
	public static AlipayWapResult notifyResult(HttpServletRequest request) throws Exception{
		AlipayWapResult result = new AlipayWapResult();
		Map<String,String> params = new HashMap<String,String>();
		Map requestParams = request.getParameterMap();
		for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i]
						: valueStr + values[i] + ",";
			}
			//乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
			//valueStr = new String(valueStr.getBytes("ISO-8859-1"), "UTF-8");
			params.put(name, valueStr);
		}
		
		//商户订单号
		String out_trade_no = params.get(PayConstants.OUT_TRADE_NO);
		result.setOut_trade_no(out_trade_no);
		//支付宝交易号
		String trade_no = params.get(PayConstants.AliPay.TRADE_NO);
		result.setTrade_no(trade_no);
		//交易状态
		String trade_status = params.get(PayConstants.AliPay.TRADE_STATUS);
		result.setTrade_status(trade_status);
		//交易金额
		String price = params.get(PayConstants.AliPay.TRADE_PRICE);
		result.setPrice(new BigDecimal(price));
		//获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以上仅供参考)//

		if(AlipayAppNotify.verifyNotify(params)){//验证成功
			if(trade_status.equals(PayConstants.AliPay.TRADE_FINISHED)){
				result.setVerify_result(true);
			} else if (trade_status.equals(PayConstants.AliPay.TRADE_SUCCESS)){
				result.setVerify_result(true);
			}
		}else{//验证失败
			result.setVerify_result(false);
		}
		return result;
	}
	
	/**
	 * 支付宝退款的异步回调
	 * @param request
	 * @return
	 * @throws Exception
	 */
	/*public static AlipayRefundResult notifyRefund(HttpServletRequest request) throws Exception{
		Map<String, String> params= DCHttpUtils.getParams(request);
		AlipayRefundResult result=new AlipayRefundResult();
		if (AlipayNotify.verifyNotifyMD5(params)) {
			result.setBatchNo(params.get("batch_no"));
			result.setResultDetails(params.get("result_details"));
			result.setVerifyResult(true);
		}else {
			result.setVerifyResult(false);
		}
		return result;
	}*/
}
